package com.triptogether.utils.ws;

import java.io.IOException;

import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.client.methods.HttpPost;
import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase;
import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;
import ch.boye.httpclientandroidlib.params.HttpConnectionParams;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.util.EntityUtils;

import com.triptogether.utils.log.Logger;

public class WebServiceUtils {

	private static final String TAG = Logger.makeLogTag(WebServiceUtils.class.getName());
	private static final int CONNECTION_TIME_OUT = 5 * 1000; // wait until a connection is established	
	private static final int SOCKET_TIME_OUT = 5 * 1000; // wait for retrieving data
	
	/**
	 * Execute a webservice request.</br>
	 * 
	 * @param request
	 *            {@link HttpRequestBase} object for the method to know what to
	 *            execute
	 * @return {@link WebServiceResult} object from the Web Service
	 * @throws IOException 
	 * @throws Exception 
	 */
	private static WebServiceResult executeWs(HttpRequestBase request) {
		WebServiceResult webServiceResult = new WebServiceResult();
		HttpClient client = null;

		// Init the HttpClient
		client = new DefaultHttpClient();
		
		// Set connection and socket time out
		HttpParams params = client.getParams();		
		HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIME_OUT);
		HttpConnectionParams.setSoTimeout(params, SOCKET_TIME_OUT);

		// Execute the request and get the response
		HttpResponse response = null;

		try {
			// Execute the request and get the result from the response
			response = client.execute(request);
			String responseString = EntityUtils.toString(response.getEntity());
			
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == WebServiceResult.HTTP_STATUS_OK) {
				// If the webservice succeeded to execute initialize the WebServiceResult with status ok
				webServiceResult.setOK(responseString);
			} else {
				// otherwise, initialize the WebServiceResult with status error
				webServiceResult.setError(statusCode, response.getStatusLine().getReasonPhrase());
			}
		} catch (Exception e) {
			// Init the WebServiceResult with status failed, because the request
			// has been failed to execute
			webServiceResult.setFailed(e.getMessage());
			Logger.LOGE(TAG, e.getMessage(), e);
			response = null;
		} finally {
			// Close the connection no matter what
			client.getConnectionManager().shutdown();
		}

		return webServiceResult;
	}

	private static WebServiceResult WsPost(String url) {
		url = filterUrl(url);
		HttpPost request = new HttpPost(url);
		WebServiceResult wsResult = executeWs(request);

		return wsResult;
	}


	public static WebServiceResult WsGet(String url) {
		url = filterUrl(url);
		HttpGet request = new HttpGet(url);
		WebServiceResult wsResult = executeWs(request);

		return wsResult;
	}
	
	/**
	 * Register the user in TripTogether Servers
	 * 
	 * @param facebookId
	 * @param userName
	 * @param regId
	 * @return The user id on TripTogether servers
	 * @throws IOException
	 */
	public static WebServiceResult registerUserLogedIn(String facebookId, String userName, String regId) {
		String url = String.format("%s/%s/%s/%s", WebServiceCons.REGISTER_USER_LOGGED_IN_URL,
		                           facebookId, userName, regId);
		return WsPost(url);
	}
	
	public static WebServiceResult registerUserLogedOut(String userId) {
		String url = String.format("%s/%s", WebServiceCons.REGISTER_USER_LOGGED_OUT_URL, userId);
		
		return WsPost(url);
	}
	
	public static WebServiceResult sendChatMessage(String fromUserFacebookId, String toUserFacebookId, String message) {
		String url = String.format("%s/%s/%s/%s", WebServiceCons.SEND_CHAT_MESSAGE_URL, fromUserFacebookId, toUserFacebookId, message);

		return WsPost(url);
	}

	private static String filterUrl(String url) {
		url = url.replace(" ", "%20");
		return url;
	}
}
